import type { Coordinate, PointData } from '@/types'

export function pointFilter(coordinates: PointData[]) {
  console.log(coordinates)

  const filtered = coordinates.slice()

  let i = 1
  while (i < filtered.length - 1) {
    const a = filtered[i - 1]
    const b = filtered[i]
    const c = filtered[i + 1]

    const angle = calculateAngle(a, b, c)
    if (angle < 10 && !filtered[i].topId) {
      filtered.splice(i, 1)
      i = 1
    } else {
      i++
    }
  }

  return filtered
}

function calculateAngle(a: Coordinate, b: Coordinate, c: Coordinate) {
  // 向量 AB 和 BC
  const ab = { x: b.x - a.x, y: b.y - a.y }
  const bc = { x: c.x - b.x, y: c.y - b.y }

  // 向量的点积
  const dotProduct = ab.x * bc.x + ab.y * bc.y

  // 向量的模
  const magnitudeAB = Math.sqrt(ab.x * ab.x + ab.y * ab.y)
  const magnitudeBC = Math.sqrt(bc.x * bc.x + bc.y * bc.y)

  // 夹角的余弦值
  const cosTheta = dotProduct / (magnitudeAB * magnitudeBC)

  // 使用 Math.acos 计算夹角（弧度）
  const angleRadians = Math.acos(cosTheta)

  // 将弧度转换为角度
  const angleDegrees = angleRadians * (180 / Math.PI)

  return angleDegrees
}
